const fs = require('fs');
const path = require('path');

// 将请求路径和方法映射到 data 目录结构
const getDirName = (req) => {
  const method = req.method;
  const lastField = req.path.split('/').filter(part => part !== '').pop();
  return path.join(__dirname, '../data', `${lastField}_${method}`);
};

// 加载 config.json
const loadConfig = (dirPath) => {
  const configPath = path.join(dirPath, 'config.json');
  if (!fs.existsSync(configPath)) return [];
  return require(configPath);
};

// 匹配条件
const matchCondition = (req, condition) => {
  if (!condition) return true;
  const source = req.method === 'GET' ? req.query : req.body;
  // 查询参数匹配
  if (condition) {
    for (const [key, value] of Object.entries(condition)) {
      if (source[key] !== value) return false;
    }
  }

  return true;
};

// 中间件逻辑
const conditionalHandler = (req, res, next) => {

  const dirPath = getDirName(req);
  const config = loadConfig(dirPath);

  if (!config || config.length === 0) {
    return next(); // 使用默认路由或返回 404
  }

  const matchedRule = config.find(rule => matchCondition(req, rule.condition));

  const filePath = path.join(dirPath, matchedRule.responsePath);
  console.log(`Reading file: ${filePath}`); // 调试输出

  const responseData = JSON.parse(fs.readFileSync(filePath, 'utf-8'));

  res.status(parseInt(responseData.status)).json(responseData);
};

module.exports = conditionalHandler;